package zozopo.filter;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class WebsiteFilter implements Filter{
	private static final Log logger = LogFactory.getLog(LogFactory.class);
	int refrshLimit = 100; //1000 = 1秒
	
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain filter) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;
		HttpSession session = request.getSession();
		//request.gets
		
		//request.setCharacterEncoding("UTF-8");
		//response.setCharacterEncoding("UTF-8");
		
		if(session.isNew()){
			//取得上个界面连接.只能取得jsp,html...之类。 不能取得action.类
			//String uri = request.getServletPath();
			//session.setAttribute("uri", uri);
			
			long refreshtime = System.currentTimeMillis();
			//System.out.println(uri);
			session.setAttribute("refreshtime", refreshtime);
			filter.doFilter(arg0, arg1);
		}else{
			//String uri = request.getServletPath();
			//System.out.println(uri);
			//session.setAttribute("uri", uri);
			
			if(session.getAttribute("refreshtime") == null){
				session.setAttribute("refreshtime", new Long(0));
			}
			long refreshtime = (Long) session.getAttribute("refreshtime");
			long currentTimeMillis = System.currentTimeMillis();
			session.setAttribute("refreshtime", currentTimeMillis);
			long interval = currentTimeMillis - refreshtime;
			
			// 若debug模式开启，则输出debug 信息
	        if (logger.isDebugEnabled()) {
	        	System.out.println("currentTimeMillis:"+currentTimeMillis +" refreshtime:"+refreshtime +" interval:" + interval);
	        }
			
			if(interval>=refrshLimit ){
				filter.doFilter(arg0, arg1);
			}else{
				System.out.println("user refres too fast!");
			}
		}//*/
		
		
		
		//filter.doFilter(arg0, arg1); 	
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
